import 'dart:async';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:merchants/models/settings.dart';
import 'package:merchants/env.dart';

/// 全局配置 Provider：聚合 baseUrl、appVersion 等可扩展设置
final settingsProvider =
    StateNotifierProvider<SettingsNotifier, AsyncValue<Settings>>(
  (ref) => SettingsNotifier(),
);

class SettingsNotifier extends StateNotifier<AsyncValue<Settings>> {
  SettingsNotifier() : super(const AsyncValue.loading()) {
    _load();
  }

  final Completer<void> _loaded = Completer<void>();
  Future<void> get loaded => _loaded.future;

  Future<void> _load() async {
    try {
      // 1) 编译期注入最高优先
      String baseUrl;
      if (Env.fullBaseUrl.isNotEmpty) {
        baseUrl = Env.fullBaseUrl;
      } else {
        // 2) .env / SharedPreferences
        await dotenv.load(fileName: '.env');
        final prefs = await SharedPreferences.getInstance();
        baseUrl = prefs.getString('baseUrl') ?? dotenv.env['BASE_URL'] ?? '';
        if (baseUrl.isEmpty) {
          throw Exception('BASE_URL 未配置');
        }
      }

      final appVersion =
          (await PackageInfo.fromPlatform()).version;

      state = AsyncValue.data(
        Settings(baseUrl: baseUrl, appVersion: appVersion),
      );
      if (!_loaded.isCompleted) _loaded.complete();
    } catch (e, st) {
      state = AsyncValue.error(e, st);
      if (!_loaded.isCompleted) _loaded.completeError(e, st);
    }
  }

  /// 更新 baseUrl 并持久化
  Future<void> updateBaseUrl(String url) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('baseUrl', url);

    final current = state.valueOrNull;
    if (current != null) {
      state = AsyncValue.data(current.copyWith(baseUrl: url));
    } else {
      state = AsyncValue.data(
        Settings(baseUrl: url, appVersion: 'unknown'),
      );
    }
  }

  /// 更新 darkMode 开关示例，可扩展更多字段
  void toggleDarkMode() {
    final current = state.valueOrNull;
    if (current == null) return;
    state = AsyncValue.data(
      current.copyWith(darkMode: !current.darkMode),
    );
  }
} 